package com.inspsys.inspection.service.impl;

import com.alibaba.fastjson2.util.DateUtils;
import com.inspsys.common.utils.DictUtils;
import com.inspsys.inspection.domain.bo.TaskBO;
import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.draw.LineSeparator;

import io.jsonwebtoken.lang.Collections;

import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;

/**
 * 生成pdf
 */
@Service
public class PdfGeneratorService {

    /**
     * 生成pdf
     * 
     * @return
     */
    public byte[] generateInspectionReport(TaskBO taskBO) {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            // 创建 PDF 文档，设置页面大小为 A4
            Document document = new Document(PageSize.A4);
            PdfWriter.getInstance(document, byteArrayOutputStream);
            document.open();

            // 标题部分
            String fontPath = "fonts/simsun.ttc,0"; // 替换为实际字体路径
            BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font titleFont = new Font(baseFont, 16, Font.BOLD);

            document.add(Chunk.NEWLINE); // 添加空行
            Paragraph title = new Paragraph("无人化巡检智能检测报告", titleFont);
            title.setAlignment(Element.ALIGN_CENTER);
            document.add(title);

            document.add(Chunk.NEWLINE); // 添加空行

            // 基本信息部分
            Font infoTitleFont = new Font(baseFont, 12, Font.BOLD);
            Font infoFont = new Font(baseFont, 12, Font.NORMAL);
            Paragraph infoParagraph = new Paragraph();
            infoParagraph.add(new Chunk("工单编号：", infoTitleFont));
            infoParagraph.add(new Chunk(taskBO.getOrderNumber(), infoFont));
            document.add(infoParagraph);

            infoParagraph = new Paragraph();
            infoParagraph.add(new Chunk("任务专业：", infoTitleFont));
            String taskType = DictUtils.getDictLabel("insp_task_type", taskBO.getTaskType());
            infoParagraph.add(new Chunk(taskType, infoFont));
            document.add(infoParagraph);

            infoParagraph = new Paragraph();
            infoParagraph.add(new Chunk("巡检区段：", infoTitleFont));
            infoParagraph.add(new Chunk(taskBO.getSection(), infoFont));
            document.add(infoParagraph);

            infoParagraph = new Paragraph();
            infoParagraph.add(new Chunk("作业平台：", infoTitleFont));
            String platform = DictUtils.getDictLabel("insp_task_platform", taskBO.getPlatform());
            infoParagraph.add(new Chunk(platform, infoFont));
            document.add(infoParagraph);

            infoParagraph = new Paragraph();
            infoParagraph.add(new Chunk("巡检时间：", infoTitleFont));
            String startDate = DateUtils.format(taskBO.getTaskStartTime(), "yyyy-MM-dd");
            String endDate = DateUtils.format(taskBO.getTaskEndTime(), "yyyy-MM-dd");
            infoParagraph.add(new Chunk(startDate + " 至 " + endDate, infoFont));
            document.add(infoParagraph);

            infoParagraph = new Paragraph();
            infoParagraph.add(new Chunk("作业规范：", infoTitleFont));
            infoParagraph.add(new Chunk(taskBO.getSpecifications(), infoFont));
            document.add(infoParagraph);

            document.add(Chunk.NEWLINE); // 添加空行

            // 添加双横线
            LineSeparator lineSeparator = new LineSeparator();
            lineSeparator.setLineWidth(0.3f);
            document.add(lineSeparator);
            Paragraph spacing = new Paragraph("", new Font(baseFont, 5, Font.NORMAL));
            // 设置空行的高度
            spacing.setSpacingBefore(1.2f);
            document.add(spacing);
            document.add(lineSeparator);

            document.add(Chunk.NEWLINE); // 添加空行

            Paragraph spacing1 = new Paragraph("", new Font(baseFont, 9, Font.NORMAL));

            List<String> detectList = taskBO.getDetectResultImageList();
            int length = Collections.isEmpty(detectList) ? 0 : detectList.size();

            // 检查结果部分
            document.add(new Paragraph("一、检查结果", infoTitleFont));
            spacing.setSpacingBefore(9f); // 设置空行的高度
            document.add(new Paragraph("  • 提交数据：" + length + "张", infoFont));
            document.add(new Paragraph("  • 检查合格：" + length + "张", infoFont));
            document.add(new Paragraph("  • 检查不合格：0张", infoFont));

            document.add(Chunk.NEWLINE); // 添加空行
            // 添加双横线
            lineSeparator.setLineWidth(0.3f);
            document.add(lineSeparator);
            // 设置空行的高度
            spacing.setSpacingBefore(1.2f);
            document.add(spacing);
            document.add(lineSeparator);
            document.add(Chunk.NEWLINE); // 添加空行

            // 缺陷识别结果部分
            document.add(new Paragraph("二、缺陷识别结果", infoTitleFont));
            spacing1.setSpacingBefore(9f);
            document.add(new Paragraph("  • 检测数据：" + length + "张", infoFont));
            document.add(new Paragraph("  • 缺陷数量：" + length + "张", infoFont));

            // 设置空行的高度
            spacing.setSpacingBefore(1.5f);
            document.add(spacing);

            // 表格部分
            PdfPTable table = new PdfPTable(5); // 创建5列的表格
            table.setWidthPercentage(100);
            table.setSpacingBefore(10f);

            // 表头
            Font headerFont = new Font(baseFont, 12, Font.NORMAL);
            table.addCell(createCenteredCell("序号", headerFont));
            table.addCell(createCenteredCell("专业", headerFont));
            table.addCell(createCenteredCell("缺陷类别", headerFont));
            table.addCell(createCenteredCell("缺陷位置", headerFont));
            table.addCell(createCenteredCell("缺陷图片", headerFont));

            // 获取报告日期（检测图片生成日期）
            Long lastModified = 0L;

            // 表格数据（动态生成）
            Font tableFont = new Font(baseFont, 12, Font.NORMAL);
            for (int i = 0; i < length; i++) { //
                File imageFile = new File(detectList.get(i));
                String fileName = "";
                if (imageFile.exists()) {
                    //
                    lastModified = imageFile.lastModified();
                    //
                    fileName = imageFile.getName().substring(0, imageFile.getName().lastIndexOf("."));
                }
                table.addCell(createCenteredCell(String.valueOf(i + 1), tableFont));
                table.addCell(createCenteredCell(taskType, tableFont));
                table.addCell(createCenteredCell(fileName, tableFont));
                table.addCell(createCenteredCell(taskBO.getSection(), tableFont));
                // 添加图片单元格
                PdfPCell imageCell = new PdfPCell();
                if (imageFile.exists()) {
                    Image image = Image.getInstance(imageFile.getAbsolutePath());
                    image.scaleToFit(60, 60); // 缩放图片大小
                    image.setAlignment(Element.ALIGN_CENTER); // 图片居中
                    imageCell.addElement(image);
                } else {
                    imageCell.addElement(new Phrase("图片丢失", tableFont));
                }
                table.addCell(imageCell);
            }
            document.add(table);

            document.add(Chunk.NEWLINE); // 添加空行

            // 报告日期部分
            document.add(Chunk.NEWLINE);
            if (lastModified ==0 ) {
                lastModified = System.currentTimeMillis();
            }
            Date date = new Date(lastModified);
            String reportDate = DateUtils.format(date, "yyyy年MM月dd日");
            Paragraph reportDateParagraph = new Paragraph("报告日期：" + reportDate, infoFont);
            reportDateParagraph.setAlignment(Element.ALIGN_RIGHT); // 设置段落靠右对齐
            document.add(reportDateParagraph);

            // 关闭文档
            document.close();

            return byteArrayOutputStream.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**表格居中 */
    private PdfPCell createCenteredCell(String content, Font font) {
        PdfPCell cell = new PdfPCell(new Phrase(content, font));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        return cell;
    }

    // 示例保存到文件
    public void savePdfToFile(String filePath) {
        byte[] pdfData = generateInspectionReport(new TaskBO());
        if (pdfData != null) {
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                fos.write(pdfData);
                System.out.println("PDF saved to: " + filePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        PdfGeneratorService pdfGeneratorService = new PdfGeneratorService();
        pdfGeneratorService.savePdfToFile("/Users/mac/Desktop/inspection_report.pdf");
    }
}